package com.cgah

import javax.servlet.http.HttpServletResponse
import util.converters.JSON
//import grails.converters.*;


class BidController {
    // injected
    def springSecurityService;

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [bidInstanceList: Bid.list(params), bidInstanceTotal: Bid.count()]
    }

    def create = {
        def bidInstance = new Bid()
        bidInstance.properties = params
        return [bidInstance: bidInstance]
    }

    def save = {
        def bidInstance = new Bid(params)
        if (bidInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'bid.label', default: 'Bid'), bidInstance.id])}"
            redirect(action: "show", id: bidInstance.id)
        }
        else {
            render(view: "create", model: [bidInstance: bidInstance])
        }
    }

    def show = {
        def bidInstance = Bid.get(params.id)
        if (!bidInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
        else {
            [bidInstance: bidInstance]
        }
    }

    def edit = {
        def bidInstance = Bid.get(params.id)
        if (!bidInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [bidInstance: bidInstance]
        }
    }

    def update = {
        def bidInstance = Bid.get(params.id)
        if (bidInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (bidInstance.version > version) {

                    bidInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'bid.label', default: 'Bid')] as Object[], "Another user has updated this Bid while you were editing")
                    render(view: "edit", model: [bidInstance: bidInstance])
                    return
                }
            }
            bidInstance.properties = params
            if (!bidInstance.hasErrors() && bidInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'bid.label', default: 'Bid'), bidInstance.id])}"
                redirect(action: "show", id: bidInstance.id)
            }
            else {
                render(view: "edit", model: [bidInstance: bidInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def bidInstance = Bid.get(params.id)
        if (bidInstance) {
            try {
                bidInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'bid.label', default: 'Bid'), params.id])}"
            redirect(action: "list")
        }
    }


    def asyncAddBid = {
        params.'customer.id' = springSecurityService.currentUser.id;
        params.'listing.id' = params.'listing.id';

        def bidInstance = new Bid(params);

        if (bidInstance.save(flush: true)) {
            flash.message = "Bid successfull."

            JSONResponseMessage message = new JSONResponseMessage(
                    //                    Long id,      Float amount,       Float nextMinBid,       Date dateTime,          String username
                    new BidJsonResponse(bidInstance.id, bidInstance.amount, bidInstance.nextMinBid, bidInstance.dateTime, bidInstance.customer?.username),
                    "Bid successfull.");
                response.setStatus(HttpServletResponse.SC_OK, "OK");
                response.contentType = "application/json"
                // ok i can't use this in unit testing, idfky
                // render message.encodeAsJSON()

                // see bug http://jira.grails.org/browse/GRAILS-6222
                // because grails fuking fails.
                // render message as JSON;

                // and the workaround YAY? NOT! FAIL!
                render new JSON(message);
            
        } else {
            flash.message = "Bid creation FAILED.  Verify your bid is \$0.50 more."
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST, "Bid creation FAILED.  Verify your bid is \$0.50 more.");
            //response.setContentType("application/json");
            // ok i can't use this in unit testing, idfky
                // render message.encodeAsJSON()
                // see bug http://jira.grails.org/browse/GRAILS-6222
                // because grails fuking fails.
                // render message as JSON;
            render(text: "Bid creation FAILED.  Verify your bid is \$0.50 more.")
        }
    }
}

// this is sooooooo stupid.  I must be missing something super obvious!
class JSONResponseMessage {
    def message;
    def status = HttpServletResponse.SC_OK;
    def bid;

    JSONResponseMessage(BidJsonResponse bid, String message) {
        this.message = message;
        this.bid = bid;
    }
}
